<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '编辑' : '关联渠道SKU'"
    width="600"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <div class="flex mb-4" style="min-width: 200px">
      <div class="font-bold">平台：</div>
      <div>
        <span>{{ getPlatformName(form.platform) }}</span>
      </div>
    </div>
    <div class="flex mb-4">
      <div class="font-bold w-20">商品名称：</div>
      <div>
        <span v-if="form.product_name">{{ form.product_name }}</span>
        <span v-else class="text-gray-400">输入SKU后，根据SKU查询商品名称</span>
      </div>
    </div>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="100"
      size="default"
      label-position="top"
    >
      <el-form-item label="平台产品标题" prop="type">
        <el-input v-model.trim="form.product_en_name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="店铺" prop="shop_id">
        <el-select
          v-model="form.shop_id"
          clearable
          filterable
          placeholder="请选择"
          class="w-full"
          @change="changeShop"
        >
          <el-option
            v-for="item in props.shopOptions"
            :key="item.shop_id"
            :label="item.shop_name"
            :value="item.shop_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="relative" label="渠道SKU" prop="platform_sku">
        <template #label>
          渠道SKU
          <el-tooltip placement="top">
            <template #content>
              <p>编辑操作禁止修改渠道SU和系统SKU，若需修改，可禁用该条数据后重新关联；</p>
            </template>
            <svg-icon
              class="absolute left-[80px] top-1"
              icon-class="QuestionFilled"
            ></svg-icon>
          </el-tooltip>
          <span class="text-[#FF0000] ml-6">注：区分字母大小写</span>
        </template>
        <el-input
          v-model.trim="form.platform_sku"
          placeholder="请输入"
          :disabled="form.id"
          clearable
        />
        <el-checkbox
          v-model="form.is_default_channel_sku"
          :true-label="1"
          :false-label="0"
          size="large"
          >是否默认渠道SKU（用于创建头程单时获取默认渠道SKU）</el-checkbox
        >
        <el-checkbox
          v-if="form.platform == 'amazon'"
          v-model="form.is_sync_title"
          :true-label="1"
          :false-label="0"
          size="large"
          >停止同步Listing标题（默认开启，勾选后，将不在同步Listing标题）</el-checkbox
        >
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="ASIN" prop="alias">
            <el-input v-model.trim="form.asin" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="UPC/EAN" prop="type">
            <el-input v-model.trim="form.upc_or_ean" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作运营人员" prop="operator_user_id">
            <SelectPersonnelFilter
              class="w-full"
              placeholder="请选择销售人员"
              v-model="form.operator_user_id"
            ></SelectPersonnelFilter>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售人员" prop="operations_id">
            <SelectPersonnelFilter
              class="w-full"
              v-model="form.operations_id"
              placeholder="请选择销售人员"
              @change="changePersonel"
            ></SelectPersonnelFilter>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="SKU" prop="goods_sku">
            <el-input
              v-model.trim="form.goods_sku"
              placeholder="请输入SKU"
              :disabled="form.id"
              @blur="changeSKU(form.goods_sku)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="FNSKU">
            <el-input v-model.trim="form.fn_sku" placeholder="请输入FNSKU" />
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.platform == 'amazon'">
        <el-form-item label="透明计划">
          <VGroup>
            <el-radio-group v-model="form.is_transparent" @change="changeTransparent">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <el-select
              v-model="form.transparent_method"
              clearable
              filterable
              placeholder="透明计划获取方式"
              class="ml-10 w-[300px]"
              @change="changeTransparentMethod()"
              v-if="form.is_transparent == 1"
            >
              <el-option
                v-for="item in transparentMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </VGroup>
        </el-form-item>
        <el-form-item
          label="GTIN"
          :prop="form.is_transparent == 1 && form.transparent_method == 2 ? 'gtin' : ''"
          v-if="form.is_transparent == 1 && form.transparent_method == 2"
        >
          <el-input v-model="form.gtin" placeholder="请输入GTIN" />
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="RelevanceChannel">
import {
  channelSkuSave,
  channelSkuEdit,
  changeskuExist,
  existOperation,
} from "../api/index";
import { querySkuList } from "../../api/index";
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { transparentMethodOptions } from "../data.js";
import SelectPersonnelFilter from "@/components/SelectPersonnelFilter/index.vue";
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();
const platformOptions = computed(() => {
  if (!commonStore.platformOptions) {
    commonStore.getPlatformList();
  }
  return commonStore.platformOptions || [];
});

const emits = defineEmits(["query"]);

const props = defineProps({
  shopOptions: {
    type: Array,
    default: () => [],
  },
});

const getPlatformName = (platform) => {
  console.log(platformOptions.value);
  const platformObject = platformOptions.value.find((i) => i.platform_code == platform);
  if (platformObject == undefined) return;
  return platformObject.platform_name;
};

const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    shop_id: [{ required: true, message: "请选择店铺", trigger: "change" }],
    platform_sku: [{ required: true, message: "请输入渠道SKU" }],
    operations_id: [{ required: true, message: "请选择销售人员", trigger: "change" }],
    goods_sku: [{ required: true, message: "请输入SKU" }],
    gtin: [{ required: true, message: "请输入GTIN" }],
    operator_user_id: [
      { required: true, message: "请选择操作运营人员", trigger: "change" },
    ],
  },
  load: false,
  confirmAndUpdateTriggered: false, // 新增标志位
});
const {
  rules,
  form,
  visible,
  loading,
  formRef,
  load,
  confirmAndUpdateTriggered,
} = toRefs(data);
const open = async (item, platform) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (item) {
    if (item.upc && item.ean) item.upc_or_ean = `${item.upc}/${item.ean}`;
    item.operations_personnel = Number(item.operations_personnel);
    form.value = item;
  } else {
    form.value.platform = platform;
  }
  visible.value = true;
};

const changeSKU = async (val) => {
  if (!val) return;
  try {
    const res = await querySkuList({
      sku: val,
    });
    if (res.data.length == 0) {
      ElMessage.warning("暂无数据");
    }
    form.value.product_name = res.data[0].sku_cn_title;
    form.value.is_transparent = res.data[0].is_transparent_plan;
  } catch (e) {
    throw Error(e);
  }
};

const changeShop = async (val) => {
  const item = props.shopOptions.find((i) => i.shop_id == val);
  form.value.shop_name = item?.shop_name;
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (form.value.id) {
        try {
          const is_flag = await getExistOperation();
          loading.value = true;
          if (!is_flag) return;
          const res = await channelSkuEdit(form.value);
          ElMessage.success("操作成功");
          initForm();
          emits("query");
          close();
        } catch (e) {
          throw Error(e);
        } finally {
          loading.value = false;
        }
      } else {
        const is_corfirm = await handleConfirmAndUpdate();
        if (!is_corfirm) return;

        if (!confirmAndUpdateTriggered.value && form.value.platform == "amazon") {
          confirmAndUpdateTriggered.value = false;
          const is_flag = await getExistOperation();
          if (!is_flag) return;
        }
        loading.value = true;
        try {
          const res = await channelSkuSave(form.value);
          ElMessage.success("操作成功");
          initForm();
          emits("query");
          close();
        } catch (e) {
          throw Error(e);
        } finally {
          loading.value = false;
        }
      }
    }
  });
};

// 初始化
const getForm = () => {
  return {
    platform: "",
    shop_id: "",
    shop_name: null,
    platform_sku: "",
    asin: "",
    upc_or_ean: "",
    goods_sku: "",
    custom_sku: "",
    operations_id: null,
    is_notice: 0,
    is_transparent: "",
  };
};

const close = () => {
  confirmAndUpdateTriggered.value = false;
  visible.value = false;
  initForm();
};
const initForm = () => {
  form.value = getForm();
};

onMounted(() => {
  initForm();
});

defineExpose({ open });

// promise 封装二次确认
const handleConfirmAndUpdate = async () => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await changeskuExist({
        shop_id: form.value.shop_id,
        platform_sku: form.value.platform_sku,
      });
      if (res.data.length) {
        const sku = res.data.map((item) => item).join("、");
        const title = `店铺+渠道SKU已存在启用的关联数据，点击确认后，将自动禁用已有的启用数据（Amazon平台不支持自动禁用，需手动禁用后进行关联）<br> 当前渠道SKU已绑定以下SKU，请知悉！！<br> SKU：${sku}`;
        confirmAndUpdateTriggered.value = true;
        ElMessageBox.confirm(title, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true,
        })
          .then(async () => {
            resolve(true);
          })
          .catch(() => {
            resolve(false);
          });
      } else {
        resolve(true);
      }
    } catch (e) {
      reject(e); // 使用 reject 传递错误
    }
  });
};

const changeTransparentMethod = () => {
  if (form.value.transparent_method == 1) {
    form.value.gtin = "";
  }
};

const changePersonel = () => {
  if (!form.value.operator_user_id) {
    form.value.operator_user_id = form.value.operations_id;
  }
};

const cascaderProps = reactive({
  emitPath: false,
  multiple: false,
  label: "name",
  value: "user_id",
  children: "sub",
});

const filterMethod = (node, val) => {
  if (
    !!~node.text.indexOf(val) ||
    !!~node.text.toUpperCase().indexOf(val.toUpperCase())
  ) {
    return true;
  }
};

const changeTransparent = () => {
  form.value.transparent_method = "";
  form.value.gtin = "";
};

// 获取是否存在
const getExistOperation = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await existOperation({
        shop_id: form.value.shop_id,
        platform_sku: form.value.platform_sku,
        asin: form.value.asin,
        goods_sku: form.value.goods_sku,
        operator_user_id: form.value.operator_user_id,
        id: form.value.id,
      });
      if (res.data) {
        ElMessageBox.confirm(
          `平台+店铺+站点+ASIN+SKU，存在不同运营人员数据，点击确认，则已存在数据同步修改运营人员`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }
        )
          .then(async () => {
            resolve(true);
          })
          .catch((err) => {
            resolve(false);
          });
      } else {
        resolve(true);
      }
    } catch (e) {
      console.error(e);
    }
  });
};
</script>
